<!--传阅-->
<template>
  <view>
		<van-popup v-model="showCompo" closeable round position="bottom" :style="{ height: '100%' }"
				@click-close-icon="toClose" @click-overlay="toClose">
			<van-row type="flex" justify="center">
				<van-col offset="3" span="8">
					<van-cell value="传阅管理" />
				</van-col>
			</van-row>
			<view class="padding-bottom">
				<van-cell icon="newspaper-o" title="由您传阅的人员" title-class="text-bold"/>
				<view class="padding-left">
					<van-row justify="center">
						<van-col span="8">
							<van-cell title="接收人" title-class="text-bold"></van-cell>
						</van-col>
						<van-col span="8">
							<van-cell title="办理状态" title-class="text-bold"></van-cell>
						</van-col>
						<van-col span="8">
							<van-cell title="操作" title-class="text-bold"></van-cell>
						</van-col>
					</van-row>
					<van-row justify="center" v-for="item in alreadyList" :key="item.receiverName">
						<template>
							<van-col span="8">
								<van-cell :title="item.receiverName"></van-cell>
							</van-col>
							<van-col span="8">
								<van-cell :title="item.readStatus"></van-cell>
							</van-col>
							<van-col span="8">
								<van-cell title="恢复" v-if="item.isRead == '1'" @click='recovery(item.id)'
													title-class="text-blue"></van-cell>
								<van-cell title="撤回" v-else @click='withdraw(item.id)'
													title-class="text-blue"></van-cell>
							</van-col>
						</template>
					</van-row>
				</view>
			</view>

      <view class="padding-bottom">
        <van-cell icon="sort" title="传阅人员选择" title-class="text-bold"/>
        <van-checkbox-group v-model="deptChecked">
          <view v-for="(item,index) in deptList" :key="item.deptId">
            <van-cell>
              <van-checkbox shape="square" @click.native="checkAll(item.deptId, index)" ref="dept"
                            icon-size="30rpx" class="text-bold" :name="item.deptId">
                {{item.deptName}}
              </van-checkbox>
            </van-cell>
            <van-grid :column-num="3" :border="false" :center="false" class="padding-left">
              <view style="width: 100%">
                <van-checkbox-group v-model="userChecked" direction="horizontal" ref="user">
                  <van-grid-item v-for="user in item.userList" :key="user.userId">
                    <van-checkbox shape="square" :name="user.userId" icon-size="30rpx" :key="user.userId"
                                  @click.native="checkUser(user.userId, index)" >
                      {{user.userName}}
                    </van-checkbox>
                  </van-grid-item>
                </van-checkbox-group>
              </view>
            </van-grid>
          </view>
        </van-checkbox-group>
      </view>

			<view class="padding-top-lg padding-bottom-lg">
				<van-row type="flex" justify="space-around">
					<van-col span="10">
						<van-button type="info" round plain hairline block @click="toClose">取消</van-button>
					</van-col>
					<van-col span="10">
						<van-button type="info" round block @click="toSave">确定</van-button>
					</van-col>
				</van-row>
			</view>
		</van-popup>
	</view>
</template>

<script>

export default {
  props: {
    showCy: {
      type: Boolean,
      default: false
    },
    paramObject: {
      type: Object
    },
		gwTitle: {
      type: String,
      default: ''
    }
  },

  data() {
		return {
      showCompo: false,
			proInstId: '',      // openwfneededdata接口返回的proInstId
			configId: '',       // openwfneededdata接口返回的configId
			proDirId: '',       // openwfneededdata接口返回的proDirId
			title: '',          // 公文详情中的title
      alreadyList: [],    // 已传阅
      deptList: [],       // 部门
      selectedUser: [],    // 选中的用户
      deptChecked: [],
      userChecked: [],
		};
  },

	watch: {
    showCy(val) {
			this.showCompo = val
		},
		paramObject: {
			handler(nval, oval) {
				if (nval != null && JSON.stringify(nval) != "{}") {
					console.log('---------------paramObject.proInstId:' + nval.proInstId);
					this.proInstId = nval.proInstId
					this.configId = nval.configId
					this.proDirId = nval.proDirId
          // 已传阅情况
          this.getCirculate(nval.proInstId)
				}
			},
			immediate: true,
			deep: true
		},
    gwTitle(val) {
      this.title = val
    }
	},

  mounted() {
    // 传阅部门
    this.initDept()
  },

  methods: {
    // 全选
    checkAll(deptId, index) {
      let flag = this.$refs.dept[index].checked
      if(flag){
        console.log('------不选中------')
        this.selectedUser = this.selectedUser.filter(item => !this.deptList[index].userIds.includes(item))
      } else {
        console.log('------选中------')
        this.deptList[index].userIds.forEach((item, index) => {
          if(!this.selectedUser.includes(item)) {
            this.selectedUser.push(item)
          }
        })
      }
      this.userChecked = this.selectedUser
    },

    // 单个选中
    checkUser(userId, index) {
      let flag = this.selectedUser.filter(item => item == userId)
      if (flag != null && flag.length > 0) {
        console.log('--------------no---------------');
        this.$refs.dept[index].toggle(false)
        this.selectedUser = this.selectedUser.filter(item => item != userId)
      } else {
        console.log('--------------yes--------------')
        if(!this.selectedUser.includes(userId)) {
          this.selectedUser.push(userId)
        }
      }
    },

    // 已传阅情况
    getCirculate(proInstId) {
      const _this = this
      _this.$http({
        url: _this.$http.adornUrl(`/caac/oa/component/workflow/circulatecontroller/quertcirs`),
        method: 'get',
        params: _this.$http.adornParams({
          'systemKey': _this.cache.get('userInfo').systemKey,
          'systemFlag': _this.cache.get('userInfo').systemFlag,
          'proInstId': proInstId,
          'senderId': _this.cache.get('userInfo').userId
        })
      }).then(({data}) => {
        if (data.code == 200 && data.data.length > 0) {
          _this.alreadyList = data.data
        } else {
          _this.alreadyList = []
        }
      })
    },

    // 当前部门
    initDept() {
      let mainDept = this.cache.get('userInfo').mainDept
      this.deptList = [{
        'deptId': mainDept.deptId,
        'deptName': mainDept.deptName
      }]
      this.getUserList(mainDept.deptId, 0)
    },

    // 根据部门id获取用户信息
    getUserList(deptId, index) {
      const _this = this
      _this.$http({
        url: _this.$http.adornUrl(`/caac/oa/mhjcomponent/countersign/countersignController/listdeptresources`),
        method: 'get',
        params: _this.$http.adornParams({
          'systemKey': _this.cache.get('userInfo').systemKey,
          'systemFlag': _this.cache.get('userInfo').systemFlag,
          'deptId': deptId
        })
      }).then(({data}) => {
        if (data.code == 200 && data.data.length > 0) {
          _this.deptList[index].userList = data.data
          _this.deptList[index].userIds = data.data.map(item => item.userId)
        }
      })
    },

		// 取消按钮
		toClose(){
			this.$emit('closeCy', this.showCompo)
		},

		// 确定按钮
		toSave(){
      const _this = this
      console.log(_this.selectedUser.toString())
      _this.$httploading({
        url: _this.$httploading.adornUrl(`/caac/oa/component/workflow/circulatecontroller/addwfmmessage`),
        method: 'post',
        params: _this.$httploading.adornParams({
          'systemKey': _this.cache.get('userInfo').systemKey,
          'systemFlag': _this.cache.get('userInfo').systemFlag,
          'data': this.$httploading.adornData({
            'configId': _this.configId,
            'proInstId': _this.proInstId,
            'proDirId': _this.proDirId,
            'title': _this.title,
            'sender': _this.cache.get('userInfo').userId,
            'messageType': 'replyCir',  // 传阅签收时是否需要签署意见:是传replyCir,否传circulate
          }),
          'userIdList': _this.selectedUser.length > 0 ? _this.selectedUser.join(',') : ''
        })
      }).then(({data}) => {
        if (data.code == 200) {
          _this.$toast('传阅成功')
          _this.$emit('refreshBtnGroup')
          _this.$emit('closeCy')
        }
      })
		},

    // 撤回
    withdraw(id) {
      const _this = this
      _this.$httploading({
        url: _this.$httploading.adornUrl(`/caac/oa/component/workflow/circulatecontroller/deletecirculate`),
        method: 'DELETE',
        params: _this.$httploading.adornParams({
          'systemKey': _this.cache.get('userInfo').systemKey,
          'systemFlag': _this.cache.get('userInfo').systemFlag,
          'id': id
        }),
      }).then(({data}) => {
        if (data.code == 200) {
          _this.getCirculate(_this.proInstId)
          _this.$emit('refreshBtnGroup')
          _this.$toast('撤回成功')
        } else {
          _this.$toast(data.message + ' code:' + data.code)
        }
      })
    },

    // 恢复
    recovery(id) {
      const _this = this
      _this.$httploading({
        url: _this.$httploading.adornUrl(`/caac/oa/component/workflow/circulatecontroller/updateState`),
        method: 'get',
        params: _this.$httploading.adornParams({
          'systemKey': _this.cache.get('userInfo').systemKey,   // 固定值
          'systemFlag': _this.cache.get('userInfo').systemFlag, // 固定值
          'id': id
        }),
      }).then(({data}) => {
        if (data.code == 200) {
          _this.getCirculate(_this.proInstId)
          _this.$toast('恢复成功')
        } else {
          _this.$toast(data.message + ' code:' + data.code)
        }
      })
    },

	},

}
</script>

<style>
	.action{
		width: auto !important;
		max-width: 150rpx !important;
	}

	.van-checkbox--horizontal {
		margin-right: 2px;
	}

	/deep/ .van-grid-item__content {
	    display: -webkit-box;
	    display: -webkit-flex;
	    display: flex;
	    -webkit-box-orient: vertical;
	    -webkit-box-direction: normal;
	    -webkit-flex-direction: column;
	    flex-direction: column;
	    box-sizing: border-box;
	    height: 100%;
	    padding: 10px 8px;
	    background-color: #fff;
	}

  .van-action-sheet{
    z-index: 9999;
    min-height: 80%;
  }
  .search-add{
    position: fixed;
    height: 120rpx;
    width: 100%;
    z-index: 90;
  }
  .content{
    margin: 120rpx 0;
  }
  .bottom-btn{
    background-color: #FFFFFF;
    padding: 15rpx 0;
    position: fixed;
    width: 100%;
    height: 120rpx;
    bottom: 0;
    z-index: 999;
  }
  .popup-box{
    display: block;
    width: 100%;
    height: auto;
    padding:100rpx 0 20rpx;
  }
  /deep/ .van-cell__title {
    min-width: 20% !important;
  }
</style>
